package com.project.controller;

import com.github.pagehelper.PageInfo;
import com.project.bean.ProductBean;
import com.project.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.time.LocalDate;

/**
 * @author lyl
 * description:
 */
@RestController
@RequestMapping("product")
public class ProductController {

    @Autowired
    private IProductService iProductService;

    @RequestMapping("findByPage")
    public PageInfo<ProductBean> findProductByPage(int pageNo, String productName, LocalDate startDate, LocalDate endDate, String productStatue) {
        //查询情况下默认为查看上架商品
        if (productStatue == null || productStatue.equals("")) {
            productStatue = "上架";
        }
        return iProductService.findByPage(pageNo, productName, startDate, endDate, productStatue);
    }

    @RequestMapping("findById")
    public ProductBean findProductById(int productId) {
        return iProductService.findByProductId(productId);
    }

    @RequestMapping("updateProductStatue")
    public String update(int productId, String productStatue) {
        iProductService.updateProductStatue(productId, productStatue);
        return "ok";
    }

    /**
     * 文件上传
     *
     * @param mf
     * @return
     * @throws Exception
     */
    @RequestMapping("upload")
    public String upload(@RequestParam("pic") MultipartFile mf, ProductBean productBean) throws Exception {
        //得到上传文件名
        String fileName = mf.getOriginalFilename();
        //将文件名以时间毫秒数重命名
        fileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
        //得到上传文件存放目录的真实路径
        URL url = Thread.currentThread().getContextClassLoader()
                .getResources("static/html/imgs").nextElement();
        String filePath = URLDecoder.decode(url.getFile(), "utf-8");
        //将上传文件写入指定的服务器文件
        mf.transferTo(new File(filePath + "/" + fileName));
        productBean.setProductImg(fileName);
        //进行添加操作
        iProductService.addNewProduct(productBean);
        return "ok";
    }

    @RequestMapping("updateProductPrice")
    public String updatePrice(int productId, int productPrice) {
        iProductService.updateProductPrice(productId, productPrice);
        return "ok";
    }

}

